package com.jin.工厂模式.简单工厂模式.违背;

import com.alibaba.fastjson.JSON;
import com.jin.工厂模式.简单工厂模式.违背.card.IQiYiCardService;
import com.jin.工厂模式.简单工厂模式.违背.coupon.CouponResult;
import com.jin.工厂模式.简单工厂模式.违背.coupon.CouponService;
import com.jin.工厂模式.简单工厂模式.违背.goods.DeliverReq;
import com.jin.工厂模式.简单工厂模式.违背.goods.GoodsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PrizeController {
    public Logger logger=LoggerFactory.getLogger(PrizeController.class);
    //出参方法
    public AwardRes awardToUser(AwardReq req){
        String reqJson = JSON.toJSONString(req);
        AwardRes awardRes = null;
        try {
            logger.info("奖品发放开始{}。req:{}",req.getUid(),reqJson);
            //按照不同的类型发放商品，1.优惠券 2.实物商品 3.兑换卡
            if (req.getAwardType()==1){//发放商品的优惠券
                CouponService couponService = new CouponService();
                CouponResult couponResult = couponService.sendCoupon(req.getUid(), req.getAwardNumber(), req.getBizId());
                if ("0000".equals(couponResult.getCode())){
                     awardRes = new AwardRes("0000", "发放成功");
                }else {
                    new AwardRes("0001",couponResult.getInfo());
                }
            }else if (req.getAwardType()==2){
                GoodsService goodsService = new GoodsService();
                DeliverReq deliverReq = new DeliverReq();
                deliverReq.setUserName(queryUserName(req.getUid()));
                deliverReq.setUserPhone(queryUserPhoneNumber(req.getUid()));
                deliverReq.setSku(req.getAwardNumber());
                deliverReq.setOrderId(req.getBizId());
                deliverReq.setConsigneeUserName(req.getExtMap().get("consigneeUserName"));
                deliverReq.setConsigneeUserPhone(req.getExtMap().get("consigneeUserPhone"));
                deliverReq.setConsigneeUserAddress(req.getExtMap().get("consigneeUserAddress"));
                Boolean isSuccess = goodsService.deliverGoods(deliverReq);
                if (isSuccess){
                    awardRes = new AwardRes("0000", "发放成功");
                }else {
                    awardRes = new AwardRes("0001", "发放失败");
                }
            }else if (req.getAwardType()==3){
                String bindMobileNumber = queryUserPhoneNumber(req.getUid());
                IQiYiCardService iQiYiCardService = new IQiYiCardService();
                iQiYiCardService.grantToken(bindMobileNumber,req.getAwardNumber());
                awardRes = new AwardRes("0000", "发放成功");
            }
            logger.info("奖品发放完成{}。",req.getUid());
         //产生异常不向上抛出，自己捕获
        }catch (Exception e){
            logger.error("奖品发放失败{}。req:{}",req.getUid(),reqJson,e);
            new AwardRes("0001",e.getMessage());
        }
        return awardRes;
    }
    private String queryUserName(String uId) {
        return "花花";
    }

    private String queryUserPhoneNumber(String uId) {
        return "15200101232";
    }
}
